import logging
import time
from django.test import TestCase

from dingtalk_service import yida_client
from yida_app_service.utils import common_utils
from .custom_db_utils import CustomDBTool, CustomDataSourceManager
from django.db import connections

logger = logging.getLogger(__name__)

class YidaTest(TestCase):

    def setUp(self) -> None:
        print("开始测试...")
        return super().setUp()
    
    def test_custom_manager_init(self):
        # linanzjz_ds = CustomDataSourceManager.get_connection("linanzjz_db") # 初始化已经写在module里了
        # cursor = linanzjz_ds.cursor()
        # 执行SQL语句
        custom_db_tool = CustomDBTool("linanzjz_db")
        # 获取结果
        # rows = custom_db_tool.execute_query("SELECT * FROM tb_person",return_dict=True)
        # CustomDataSourceManager.trim(rows)
        # for row in rows:
        #     print(row)  # 这将打印出每一行的内容
        update_sql = f"update tb_person set name = '王将军' where id = {custom_db_tool.anti_sql_injection}"
        affected_row = custom_db_tool.execute_update(update_sql,[1])
        print(f"The affected row number is {affected_row}")

    def test_custom_manager_query(self):
        custom_db_tool = CustomDBTool("nanxing_db")
        query_sql = """
        SELECT ReportNum, SampleNum, EntrustNum, b.Name AS TestItemName, TestItemParmName, ProjectNum, ProjectName, EntrustUnitName, SendSampleMan, EntrustDate, Sizes, Conclusion, NeedChargeMoney, SysPrimaryKey, is_async
        FROM EntrustBills a
        JOIN testitems b ON a.Code = b.Code
        WHERE a.EntrustDate BETWEEN '2024-09-01' AND '2024-09-18'
        AND a.ProjectName LIKE '%%'
        AND a.ProjectNum LIKE '%%'
        AND (a.is_async IS NULL OR a.is_async = 1 OR a.is_async = 0)
        ORDER BY a.SysPrimaryKey DESC
        OFFSET 0 ROWS
        FETCH NEXT 10 ROWS ONLY;
        """
        rows = custom_db_tool.execute_query(query=query_sql,return_dict=True)
        CustomDataSourceManager.trim(rows=rows)
        # CustomDataSourceManager.reencode(rows=rows,source="UTF-8",target="UTF-8")
        for row in rows:
            print(row) 

    def test_linanzjz_remote_db_server(self): 
        '''
        10.8.0.13-VPN远程服务器连接测试成功
        '''
        linanzjz_db_tool = CustomDBTool("linanzjz_db")
        rows = linanzjz_db_tool.execute_query("select * from sysProjectInfomationLib")
        for row in rows:
            print(row)

    def test_linanzjz_db_sync_to_yida(self):
        '''
        同步sqlserver2000到宜搭数据库测试
        '''
        # @test 检索三条数据同步到宜搭
        form_uuid = 'FORM-38C305CFD3D14A8B99984C59FE48E537J8SW'
        admin_user_id = yida_client.admin_user_id
        linanzjz_db_tool = CustomDBTool(f"linanzjz_db")
        dict_rows = linanzjz_db_tool.execute_query("select top 3 * from sysProjectInfomationLib",return_dict=True)
        for dict_row in dict_rows:
            yida_client.create_form_data(form_uuid, admin_user_id, {
                "radioField_lw60e641": "立项项目",
                "textField_m0f2jc6b": dict_row.get("projectNum", ""),
                "textField_m0f2jc6c": "同步",
                "textField_lvhea611": dict_row.get("projectName"),
                "textField_lvhea612": dict_row.get("entrustUnit"),
                "textField_lwylsxhz": dict_row.get("constractUnit"),
                "textField_lvhea62s": dict_row.get("witnessUnit"),
                "textField_lvhea628": dict_row.get("constractionUnit"),
                "textField_lvhea620": dict_row.get("sendSampleMan"),
                "textField_lwzspie1": dict_row.get("sendSampleManTel"),
                "textField_lvhea62z": dict_row.get("witnessMan"),
                "textField_lzw538la":"/"
            })

    def test_update_project_rowcount(self):
        custom_db_tool = CustomDBTool("linanzjz_db")
        update_sql = "update sysProjectInfomationLib set projectName = '临安测试工程ggbond',CreateDate = CONVERT(DATETIME, '2024-09-30 00:00:00', 120),ProjectKey = '330185',projectAddress = '',entrustUnit = '测试委托单位',entrustUnitLinkMan = '徐家峰',entrustUnitLinkManTel = '13867300992',constractUnit = '测试建设单位',constractUnitMan = '',constractUnitManTel = '',constractionUnit = '测试施工单位',constractionUnitMan = '',constractionUnitManTel = '',witnessUnit = '浙江简治信息技术有限公司',witnessMan = 'wly',witnessManTel = '15858153121' where projectNum = '2400086'"
        affected_row = custom_db_tool.execute_update(update_sql,[])
        print(f"The affected row number is {affected_row}")

    def test_sync_handle_redis_lock(self):
        redis_lock = common_utils.SyncHandleRedisLock("yida_sync:projectNum:000")
        # 尝试获取锁
        if redis_lock.acquire():
            logger.debug("获取锁成功")
            try:
                # 执行需要加锁的操作
                time.sleep(12)  # 模拟操作
            finally:
                redis_lock.release()  # 释放锁
                logger.debug("锁已释放")
        else:
            logger.debug("获取锁失败，锁已被其他进程占用")    